package cn.itlaobing.web.filter;
import cn.itlaobing.web.servlet.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Created by admin on 2017/11/4.
 */
public class AuthenFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=null;
        HttpServletResponse resp=null;
        if (req instanceof HttpServletRequest){
            req=(HttpServletRequest)request;
        }
        if (resp instanceof  HttpServletResponse){
            resp=(HttpServletResponse) response;
        }
            String requestUrl=req.getRequestURI();
        if("/signin.jsp".equals(requestUrl) || "/auth/signin".equals(requestUrl) || requestUrl.startsWith("/assets")){
            chain.doFilter(req,resp);//放行
        }else{
            //判断是否登录
            if(req.getSession().getAttribute(Constants.CURRENT_USER)==null){
                //跳转到登陆页面
                req.getSession().setAttribute("msg","请登录后再操作！");
                resp.sendRedirect(req.getContextPath()+"/signin.jsp");
                return;
            }else{
                //如果登录，则放行
                chain.doFilter(req,resp);//放行
            }
        }
    }
    @Override
    public void destroy() {

    }
}
